<template>
  <a-modal :width="1200" body-style="padding: 10px 20px" v-model:visible="showEditDialog" :title="`${type == 'edit' ? '编辑' : '创建'}交货单-${currentItem.billNo}`" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="header">
      <p class="title">基础信息</p>
    </div>
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="10">
          <a-form-item label="供应商：" label-col-flex="100px">
            <p>{{ formInfo.supplierName }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="7" v-if="type == 'edit'">
          <a-form-item label="目的仓库：" label-col-flex="100px">
            <p>{{ formInfo.warehouseName }}({{ formInfo.warehouseCode }})</p>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item field="gmtDelivery" label="交货日期：" label-col-flex="100px">
            <a-date-picker v-model="formInfo.gmtDelivery" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item label="物流方式：" label-col-flex="100px">
            <a-select v-model="formInfo.logisticType" placeholder="">
              <a-option :value="1" label="线下配送" />
              <a-option :value="2" label="快递" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="14">
          <a-form-item label="物流跟踪号：" label-col-flex="100px">
            <a-input v-model="formInfo.logisticName" style="width: 160px; margin-right: 10px" placeholder="物流商" />
            <a-input v-model="formInfo.logisticsTrackNumber" placeholder="物流跟踪号" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item label="附件：" label-col-flex="100px">
            <div class="flex-wrap">
              <a-tag style="margin-right: 10px; margin-bottom: 10px" v-if="formInfo.attachment" color="arcoblue" @close="formInfo.attachment = ''" closable>
                <TextLimit :rows="1">{{ formInfo.attachment }}</TextLimit>
              </a-tag>
              <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="14">
          <a-form-item label="备注：" label-col-flex="100px">
            <a-textarea v-model="formInfo.remark" placeholder="" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="header flex-c">
      <p class="title">交货明细</p>
    </div>
    <a-table
      class="table-two-line"
      ref="tableRef"
      row-key="id"
      :data="filterList"
      :scroll="{
        y: 'calc(84vh - 360px)',
      }"
      size="mini"
      :summary="true"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column title="目的仓库" :width="120" fixed="left">
          <template #cell="{ record }">
            <TextLimit :val="`${record.warehouseName}(${record.warehouseCode})`" />
          </template>
        </a-table-column>
        <a-table-column title="图片" :width="60" fixed="left">
          <template #cell="{ record }">
            <ImgPopover :src="record.productImg">
              <template #con>
                <a-image width="40" height="40" fit="contain" :src="record.productImg" />
              </template>
            </ImgPopover>
          </template>
        </a-table-column>
        <a-table-column title="产品名称" :width="120" fixed="left">
          <template #cell="{ record }">
            <TextLimit :val="record.productName" />
          </template>
        </a-table-column>
        <a-table-column title="SKU/类目" :width="120" fixed="left">
          <template #cell="{ record }">
            <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
            <p>{{ record.cateName || '--' }}</p>
          </template>
        </a-table-column>
        <a-table-column title="规格名" :width="100">
          <template #cell="{ record }">
            <TextLimit :val="getProductSpecs(record)" />
          </template>
        </a-table-column>
        <a-table-column data-index="purchaseAmt" title="采购量" :width="60" />
        <a-table-column data-index="deliveryRealAmt" title="已交货数" :width="70" />
        <a-table-column :data-index="props.type == 'add' ? 'deliveryStayAmt' : 'purchaseDeliveryNoAmt'" title="未交货" :width="70" />
        <a-table-column data-index="num" :width="140">
          <template #title>
            <div class="flex-c">
              <p>
                <span class="warningColor">*</span>
                <span>本次交货</span>
              </p>
              <a-button style="margin-left: 5px" type="text" @click="setAllAmt()">全部交货</a-button>
            </div>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c" style="width: 140px">
              <a-input-number :precision="0" :min="0" :max="props.type == 'add' ? record.deliveryStayAmt : record.purchaseDeliveryNoAmt" v-model="record.num" style="width: 90px" placeholder="" />
              <icon-double-down v-if="rowIndex != filterList.length - 1" class="edit-icon" @click="setGlobal(record, 'num', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="税率" :width="60">
          <template #cell="{ record }">
            <p>{{ record.rate }}%</p>
          </template>
        </a-table-column>
        <a-table-column title="单价" :width="70">
          <template #cell="{ record }">
            <p class="price-type highlight">{{ record.priceType === 1 ? '含税' : '不含税' }}</p>
            <p>￥{{ record.price }}</p>
          </template>
        </a-table-column>
        <a-table-column data-index="value" title="本次交货金额" :width="90">
          <template #cell="{ record }">
            <p class="price-type highlight">{{ record.priceType === 1 ? '含税' : '不含税' }}</p>
            <span>￥{{ Number(record.price * (record.num || 0)).toFixed(2) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="60" fixed="right">
          <template #cell="{ record }">
            <a-popconfirm v-if="filterList.length > 1" content="确定是否移除?" @ok="removeItem(record.id)" type="error">
              <a-button type="text">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </template>
      <template #summary-cell="{ column, record }">
        <div v-if="column.dataIndex == 'value'">￥{{ totalVal }}</div>
        <div v-else-if="['purchaseAmt', 'deliveryRealAmt', 'num', 'deliveryStayAmt'].includes(column.dataIndex)">{{ record[column.dataIndex] }}</div>
        <div v-else-if="column.dataIndex == 'sku'">合计</div>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import { createDeliveryOrder, getDeliveryInfo, updateDeliveryOrder } from '@/api/purchase'
  import { parseJson } from '@/utils'

  onMounted(() => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
    type: {
      type: String,
      default: 'add',
    },
  })
  const totalVal = computed(() => {
    let val = 0
    formInfo.value.deliveryItems?.forEach((el: any) => {
      if (!el.delete) {
        let itemVal = Number(el.price || 0) * Number(el.num || 0)
        val += itemVal
      }
    })
    return val.toFixed(2)
  })
  // 考虑编辑的时候移除不能删除，只能增加delete标识的逻辑
  const filterList = computed(() => {
    return formInfo.value.deliveryItems?.filter((el: any) => !el.delete) || []
  })
  const rules = ref({
    gmtDelivery: [{ required: true, message: '请选择发货时间' }],
  })
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const submitLoading = ref(false)
  const formRef = ref()

  // 添加初始化数据
  async function setDefaultData() {
    if (props.type == 'add') {
      formInfo.value = {
        supplierId: props.currentItem.supplierId,
        supplierName: props.currentItem.supplierName,
        logisticType: 1,
        deliveryItems: JSON.parse(JSON.stringify(props.currentItem.billItems)),
      }
    } else {
      const res: any = await getDeliveryInfo({ id: props.currentItem.id })
      let detail = res?.data || {}

      let deliveryItems: Array<any> = []
      detail.billItems.forEach((el: any) => {
        let obj = JSON.parse(JSON.stringify(el))
        obj.num = obj.deliveryAmt
        delete obj.deliveryAmt
        deliveryItems.push(obj)
      })
      formInfo.value = {
        ...detail,
        deliveryItems: deliveryItems,
      }
      delete formInfo.value.billItems
    }
  }
  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment = res.data.publicUrl
    }
  }
  //设置全局
  function setGlobal(item: any, key: string, rowIndex: number) {
    const newVal = item[key]
    formInfo.value.deliveryItems.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el[key] = newVal
      }
    })
  }
  // 一键全部交货
  function setAllAmt() {
    formInfo.value.deliveryItems.forEach((el: any) => {
      el.num = props.type == 'add' ? el.deliveryStayAmt : el.purchaseDeliveryNoAmt
    })
  }
  function removeItem(id: string) {
    let index = formInfo.value.deliveryItems?.findIndex((el: any) => el.id == id)
    if (index > -1) {
      if (props.type == 'add') {
        formInfo.value.deliveryItems.splice(index, 1)
      } else {
        formInfo.value.deliveryItems[index].delete = true
      }
    }
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    if (!filterList.value.length) {
      Message.error('请最少包含一个交货明细')
      return false
    }
    for (let el of filterList.value) {
      if (!(el.num || el.num === 0)) {
        Message.error('本次交货数量必填')
        return false
      }
    }
    return true
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 保存信息
  async function submitData() {
    let valid = await validInfo()
    if (!valid) return false
    let params = JSON.parse(JSON.stringify(formInfo.value))
    let list = formInfo.value.deliveryItems?.map((el: any) => {
      let obj: any = {
        billId: el.billId,
        deliveryAmt: el.num,
        id: el.id,
        warehouseCode: el.warehouseCode,
        warehouseName: el.warehouseName,
        remark: el.remark,
        supplierName: el.supplierName,
        supplierCode: el.supplierCode,
        supplierId: el.supplierId,
      }
      if (props.type == 'edit') {
        obj.delete = el.delete ? true : false
      }
      return obj
    })
    params.deliveryItems = list
    let res: any
    if (props.type == 'edit') {
      res = await updateDeliveryOrder(params)
    } else {
      res = await createDeliveryOrder(params)
    }
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .arco-form-item {
    margin-bottom: 10px;
  }
  .header {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 10px;
    border-left: 3px solid rgba(var(--primary-6), 0.5);
    padding-left: 10px;
    .title {
      margin-right: 30px;
      width: 90px;
    }
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
